package com.guan.ordering_sys.generator.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guan.ordering_sys.common.StateCode;
import com.guan.ordering_sys.exception.BaseException;
import com.guan.ordering_sys.generator.entity.GoodsParameter;
import com.guan.ordering_sys.generator.mapper.GoodsParameterMapper;
import com.guan.ordering_sys.generator.service.GoodsParameterService;
import com.guan.ordering_sys.param.GoodsParameterAddParam;
import com.guan.ordering_sys.param.GoodsParameterUpdateParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 关远键
 * @since 2021-06-18
 */
@Service
public class GoodsParameterServiceImpl extends ServiceImpl<GoodsParameterMapper, GoodsParameter> implements GoodsParameterService {

    @Autowired
    private GoodsParameterMapper parameterMapper;

    /**
     * 添加商品参数的值
     * @author 关远键
     * @date 2021/6/25 15:30
     * @param param
     * @return int 商品参数编号
     */
    @Override
    public Long add(GoodsParameterAddParam param) {
        GoodsParameter parameter = new GoodsParameter();
        parameter.setGoodsValue(param.getValue().toJSONString())
            .setGoodsId(param.getGoodId());

        int i = parameterMapper.insert(parameter);
        if (i > 0) {
            return parameter.getGoodsParameterId();
        } else {
            throw new BaseException(StateCode.DAO_EXCEPTION);
        }

    }

    /**
     * 根据商品参数编号更新商品参数
     * @author 关远键
     * @date 2021/6/25 15:41
     * @param param
     * @return int
     */
    @Override
    public int updateById(GoodsParameterUpdateParam param) {
        GoodsParameter goods = parameterMapper.getById(param.getId());

        if (goods == null) {
            throw new BaseException(StateCode.NOT_FOUND);
        }

        goods.setGoodsValue(param.getValue().toJSONString());

        int i = parameterMapper.updateById(goods);
        if (i > 0) {
            return i;
        } else {
            throw new BaseException(StateCode.DAO_EXCEPTION);
        }

    }

    /**
     * 删除商品参数
     * @author 关远键
     * @date 2021/6/25 15:42
     * @param id
     * @return int
     */
    @Override
    public int deleteById(Long id) {
        if (parameterMapper.deleteById(id) > 0) {
            return 1;
        } else {
            throw new BaseException(StateCode.NOT_FOUND);
        }
    }

    /**
     * 根据商品编号查看该商品的所有参数
     * @author 关远键
     * @date 2021/6/25 16:13
     * @param id
     * @return java.util.List<com.guan.ordering_sys.generator.entity.GoodsParameter>
     */
    @Override
    public List<GoodsParameter> query(Long id) {
        List<GoodsParameter> paramList = parameterMapper.getByGoodsId(id);

        if (paramList.size() == 0) {
            throw new BaseException(StateCode.NOT_FOUND);
        }

        return paramList;
    }


}
